<template>
  <div class="manual-paper-container">
    <!-- 左侧题目选择区 -->
    <div class="question-selector">
      <el-card shadow="never">
        <!-- 题目筛选条件 -->
        <div class="filter-area">
          <el-form :inline="true">
            <el-form-item label="题型">
              <el-select v-model="filter.type" clearable>
                <el-option label="全部" value=""/>
                <el-option label="选择题" value="choice"/>
                <el-option label="填空题" value="blank"/>
                <el-option label="简答题" value="short_answer"/>
              </el-select>
            </el-form-item>
            <el-form-item label="难度">
              <el-select v-model="filter.difficulty" clearable>
                <el-option label="全部" value=""/>
                <el-option v-for="i in 5" :key="i" :label="['容易','偏易','中等','较难','困难'][i-1]" :value="i"/>
              </el-select>
            </el-form-item>
            <el-form-item label="知识点">
              <el-cascader
                v-model="filter.knowledgePath"
                :options="knowledgeTree"
                :props="{label:'name',value:'pointId'}"
                clearable
              />
            </el-form-item>
            <el-button type="primary" @click="loadQuestions">搜索</el-button>
          </el-form>
        </div>

        <!-- 题目列表 -->
        <div class="question-list">
          <el-table
            :data="questionList"
            row-key="questionId"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50"/>
            <el-table-column prop="questionTitle" label="题目标题" min-width="120"/>
            <el-table-column label="题型" width="100">
              <template #default="{row}">
                {{ questionTypeMap[row.questionType] }}
              </template>
            </el-table-column>
            <el-table-column prop="difficulty" label="难度" width="80">
              <template #default="{row}">
                <el-tag :type="['success','','warning','danger',''][row.difficulty-1]">
                  {{ ['容易','偏易','中等','较难','困难'][row.difficulty-1] }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{row}">
                <el-button type="text" @click="previewQuestion(row)">预览</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.current"
            :page-sizes="[10, 20, 50]"
            :page-size="pagination.size"
            layout="total, sizes, prev, pager, next"
            :total="pagination.total"
          />
        </div>
      </el-card>
    </div>

    <!-- 右侧试卷编辑区 -->
    <div class="paper-editor">
      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span>试卷编辑</span>
          <el-button style="float: right" type="primary" @click="submitPaper">保存试卷</el-button>
        </div>

        <!-- 试卷基本信息 -->
        <el-form :model="paperForm" label-width="80px">
          <el-form-item label="试卷名称" required>
            <el-input v-model="paperForm.name"/>
          </el-form-item>
          <el-form-item label="试卷描述">
            <el-input type="textarea" v-model="paperForm.description"/>
          </el-form-item>
        </el-form>

        <!-- 已选题目 -->
        <el-divider>题目列表</el-divider>
        <draggable v-model="selectedQuestions" handle=".drag-handle">
          <div v-for="(q, index) in selectedQuestions" :key="q.questionId" class="selected-question">
            <div class="question-header">
              <i class="el-icon-rank drag-handle" style="cursor: move"/>
              <span>第{{ index + 1 }}题 ({{ questionTypeMap[q.questionType] }})</span>
              <el-input-number
                v-model="q.score"
                :min="1"
                :max="20"
                size="mini"
                style="margin-left: 10px"
              />
              <el-button
                type="text"
                icon="el-icon-delete"
                style="color: #F56C6C; margin-left: 10px"
                @click="removeQuestion(index)"
              />
            </div>
            <div class="question-content">
              {{ q.questionTitle }}
            </div>
          </div>
        </draggable>

        <!-- 试卷统计 -->
        <el-divider>试卷统计</el-divider>
        <div class="paper-stats">
          <div>总题数: {{ selectedQuestions.length }}</div>
          <div>总分: {{ totalScore }}</div>
          <div>题型分布:
            <span v-for="(count, type) in typeDistribution" :key="type">
              {{ questionTypeMap[type] }}: {{ count }}题
            </span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 题目预览对话框 -->
    <el-dialog :visible.sync="previewVisible" title="题目预览" width="70%">
      <question-preview :question="currentQuestion"/>
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
// import QuestionPreview from './components/QuestionPreview.vue'

export default {
  // components: { draggable, QuestionPreview },
  components: { draggable },
  data() {
    return {
      // 筛选条件
      filter: {
        type: '',
        difficulty: '',
        knowledgePath: []
      },
      // 题目列表
      questionList: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 已选题目
      selectedQuestions: [],
      // 试卷表单
      paperForm: {
        name: '',
        description: ''
      },
      // 预览相关
      previewVisible: false,
      currentQuestion: null,
      // 知识点树
      knowledgeTree: [],
      // 题型映射
      questionTypeMap: {
        choice: '选择题',
        blank: '填空题',
        short_answer: '简答题'
      }
    }
  },
  computed: {
    totalScore() {
      return this.selectedQuestions.reduce((sum, q) => sum + (q.score || 1), 0)
    },
    typeDistribution() {
      return this.selectedQuestions.reduce((acc, q) => {
        acc[q.questionType] = (acc[q.questionType] || 0) + 1
        return acc
      }, {})
    }
  },
  created() {
    this.loadKnowledgeTree()
    this.loadQuestions()
  },
  methods: {
    // 加载知识点树
    async loadKnowledgeTree() {
      const res = await this.$api.getKnowledgeTree()
      this.knowledgeTree = res.data
    },
    // 加载题目列表
    async loadQuestions() {
      const params = {
        ...this.filter,
        pageNum: this.pagination.current,
        pageSize: this.pagination.size
      }
      if (params.knowledgePath && params.knowledgePath.length > 0) {
        params.pointId = params.knowledgePath[params.knowledgePath.length - 1]
      }
      const res = await this.$api.getQuestionList(params)
      this.questionList = res.data.list
      this.pagination.total = res.data.total
    },
    // 表格选择变化
    handleSelectionChange(selection) {
      const newSelected = selection.filter(newItem =>
        !this.selectedQuestions.some(existing => existing.questionId === newItem.questionId)
      )
      this.selectedQuestions = [
        ...this.selectedQuestions,
        ...newSelected.map(q => ({ ...q, score: 1 }))
      ]
    },
    // 移除题目
    removeQuestion(index) {
      this.selectedQuestions.splice(index, 1)
    },
    // 预览题目
    previewQuestion(question) {
      this.currentQuestion = question
      this.previewVisible = true
    },
    // 分页变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.loadQuestions()
    },
    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadQuestions()
    },
    // 提交试卷
    async submitPaper() {
      if (!this.paperForm.name) {
        this.$message.error('请输入试卷名称')
        return
      }
      if (this.selectedQuestions.length === 0) {
        this.$message.error('请至少选择一道题目')
        return
      }

      const payload = {
        paper: this.paperForm,
        questions: this.selectedQuestions.map((q, index) => ({
          questionId: q.questionId,
          score: q.score,
          order: index + 1
        }))
      }

      try {
        await this.$api.savePaper(payload)
        this.$message.success('试卷保存成功')
        this.$router.push('/paper/list')
      } catch (error) {
        this.$message.error('保存失败')
      }
    }
  }
}
</script>

<style scoped>
.manual-paper-container {
  display: flex;
  height: calc(100vh - 120px);
}

.question-selector {
  width: 60%;
  padding-right: 15px;
  overflow-y: auto;
}

.paper-editor {
  width: 40%;
  overflow-y: auto;
}

.selected-question {
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.question-content {
  padding-left: 20px;
  color: #666;
  font-size: 14px;
}

.paper-stats {
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
}
</style>
